package top.hg.tool.modules.car.user;

import java.util.Date;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import top.hg.tool.common.config.WxMaConfiguration;
import top.hg.tool.common.exception.CarException;
import top.hg.tool.common.util.R;
import top.hg.tool.modules.car.article.ArticleEntity;
import top.hg.tool.modules.car.constant.RedisKeyConstant;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author: skh
 * @Date: 2019/7/18 10:32
 * @Description: 用户服务
 */
@Service
@Slf4j
public class UserService extends ServiceImpl<UserDao, UserEntity> {

	@Autowired
	private UserRepository userRepository;

	@Autowired
    private StringRedisTemplate redisTemplate;

    public UserVO login(String code) {
		if (StrUtil.isBlank(code)) {
			throw new CarException("code不能为空");
		}

		String appId = "wx46d02e7a8ccb93c8";
		WxMaService wxService = WxMaConfiguration.getMaService(appId);

		WxMaJscode2SessionResult session = null;
		try {
			session = wxService.getUserService().getSessionInfo(code);
			//log.info("login success,session:{},", session);
		} catch (WxErrorException e) {
			throw new CarException("小程序登录异常:" + e.getMessage());
		}

		if (session == null || StrUtil.isBlank(session.getOpenid())) {
			throw new CarException("小程序登录异常,请稍后再试");
		}

		//增加用户访问量
		Long userVisitCount = this.addUserVisit();

		UserVO userVO = new UserVO();
		userVO.setToken(session.getOpenid());
		userVO.setUserVisitCount(userVisitCount);
		log.info("用户登录,openId:{}", session.getOpenid());
		return userVO;
	}

	private void saveOrUpdateUser(WxMaJscode2SessionResult session) {
		UserEntity userByOpenId = userRepository.getUserByOpenId(session.getOpenid());
		if (userByOpenId == null) {
			//用户不存在
			UserEntity userEntity = new UserEntity();
			userEntity.setName("");
			userEntity.setPhone("");
			userEntity.setOpenId(session.getOpenid());
			userEntity.setOpenTime(1);
			userEntity.setCreateTime(new Date());
			userEntity.setUpdateTime(new Date());
			userEntity.setLoginTime(new Date());
			userEntity.setStatus(1);
			Integer id = userRepository.saveUser(userEntity);
			log.info("新增用户成功,用户id:[{}],openId:[{}]", id, session.getOpenid());
		} else {
			userByOpenId.setOpenTime(userByOpenId.getOpenTime() + 1);
			userByOpenId.setLoginTime(new Date());
			userRepository.updateUser(userByOpenId);
			log.info("修改用户成功,用户id:[{}],openId:[{}]", userByOpenId.getId(), session.getOpenid());
		}
	}


	public Long addUserVisit() {
		return redisTemplate.opsForValue().increment(RedisKeyConstant.car_user_visit_count);
	}

	public void setUserVisit(Integer initValue) {
		if (initValue == null) {
			initValue = 0;
		}
		redisTemplate.opsForValue().set(RedisKeyConstant.car_user_visit_count, String.valueOf(initValue));
		log.info("初始化用户访问量成功,初始值:{}", initValue);
	}
}
